package com.itbaizhan.controller;

import com.aliyun.tea.TeaException;
import com.itbaizhan.domain.AlarmDTO;
import com.itbaizhan.service.IMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class AlarmController {

    @Autowired
    private IMessageService iMessageService;

    @Autowired
    private JavaMailSender javaMailSender;

    @PostMapping("/alarm")
    public void  alarm( @RequestBody List<AlarmDTO> alarmDTO) throws Exception {
        if (alarmDTO != null && !alarmDTO.isEmpty()){
            for (AlarmDTO dto : alarmDTO) {
                iMessageService.sendMessage("18587781056",dto.getAlarmMessage());
                System.out.println("告警消息：" + dto.getAlarmMessage());
                System.out.println("告警规则：" + dto.getRuleName());
            }
        }
    }

    /**
     * 邮件告警
     * @param alarmDTO
     */
    @PostMapping("/email")
    public void sendEmail(@RequestBody List<AlarmDTO> alarmDTO ){


        if (alarmDTO != null && !alarmDTO.isEmpty()){
            for (AlarmDTO dto : alarmDTO) {
                // 邮件
                SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
                // 发件人
                simpleMailMessage.setFrom("877910962@qq.com");
                simpleMailMessage.setTo("877910962@qq.com");
                simpleMailMessage.setSubject(dto.getScope());
                simpleMailMessage.setText(dto.getAlarmMessage());
                javaMailSender.send(simpleMailMessage);
            }
        }
    }
}
